package com.jn.erp.wechat.student.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/9/9 11:32
 */
@RequiredArgsConstructor
@Configuration
public class StudentMpConfiguration {


    private final MiniStudentAppConfig miniStudentAppConfig;
    private static MiniStudentAppConfig configStudentFromYml;

    @PostConstruct
    public void init() {

        if (miniStudentAppConfig != null && StringUtils.isNotBlank(miniStudentAppConfig.getAppId())) {
            // 小程序参数
            configStudentFromYml = new MiniStudentAppConfig();
            BeanUtils.copyProperties(miniStudentAppConfig, configStudentFromYml);
            configStudentFromYml.setName("default");
        }
    }

    /**
     * 定义一个微信服务bean
     * */
    @Bean("parentWxMaService")
    public WxMaService parentWxMaService() {
        WxMaService service=new WxMaServiceImpl();
        List<MiniStudentAppConfig> configs=new ArrayList<>();
        configs.add(configStudentFromYml);
        service.setMultiConfigs(
                configs.stream()
                        .map(a -> {
                            WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
//                WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());
                            // 使用上面的配置时，需要同时引入jedis-lock的依赖，否则会报类无法找到的异常
                            config.setAppid(a.getAppId());
                            config.setSecret(a.getSecret());
                            config.setToken(a.getToken());
                            config.setAesKey(a.getAesKey());
                            config.setMsgDataFormat("JSON");
                            return config;
                        }).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));
        return service;
    }
}
